package com.fudan.es.aggs.request.handler.metric;

import java.util.List;

import org.elasticsearch.search.aggregations.AggregationBuilder;

import com.fudan.es.aggs.request.handler.BaseHandler;
import com.fudan.es.entity.FieldMeta;
import com.fudan.es.entity.MetricPack;
import com.fudan.es.entity.MetricPack.MetricType;
import com.fudan.framework.utils.SpringUtils;

public abstract class MetricHandler extends BaseHandler{

	public void handle(MetricPack root,MetricPack metric) {
		FieldMeta field = metric.getField();
		if(field == null) {
			throw new RuntimeException(NO_FIELD);
		}
		if(!field.getAggregatable()) {
			throw new RuntimeException(FIELD_NOT_AGGREGATABLE);
		}
		List<MetricPack> metricList = metric.getMetric();
		if(metricList != null) {
			for (MetricPack metricPack : metricList) {
				handle(metric,metricPack);
			}
		}
		if(root != null) {
			root.add(metric);
		}
	}
	abstract public AggregationBuilder build(MetricPack root);

	public static MetricHandler buildHandler(MetricType type) {
		switch (type) {
		case TERMS:
			return get(SplitHandler.class);
		case AVG:
			return get(AvgHandler.class);
		case SUM:
			return get(SumHandler.class);
		case DATE:
			return get(DateSplitHandler.class);
		default:
			return null;
		}
	}

	public static <T> T get(Class<T> clz) {
		return SpringUtils.getBean(clz);
	}
}
